﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using StudentManagement.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentManagement.Filter
{
    public class ModelStateFilter : Attribute,IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                ResponseModel result = new ResponseModel() { Result=false };

                foreach (var item in context.ModelState.Values)
                {
                    foreach (var error in item.Errors)
                    {
                        result.Msg += error.ErrorMessage + "|";
                    }
                }

                if (this.IsAjaxRequest(context.HttpContext.Request))
                {
                    context.Result = new JsonResult(result);
                }
                else
                {
                    context.Result = new ViewResult();
                }
            }
        }

        public bool IsAjaxRequest(HttpRequest request)
        {
            string header=request.Headers["X-Requested-With"];

            return "XMLHttpRequest".Equals(header);
        }
    }
}
